//
//  Tool.m
//  WebSocke
//
//  Created by ebeijia.com on 16/8/26.
//  Copyright © 2016. All rights reserved.
//

#import "JSTool.h"

@implementation JSTool

//obj to jsonString;
+(NSString *)jsonStrFrom:(id)obj{
    
    if ([NSJSONSerialization isValidJSONObject:obj])
    {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&error];
        
        if (jsonData.length>0&&error==nil)
        {
            NSString *jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            return jsonStr;
        }else{
            return nil;
        }
        
    }else{
        return nil;
    }
}

//json Data to Dic
+(NSDictionary *)jsonDicFrom:(NSData *)data{
    
    //是否为空白对象
    if(data.length == 0) return nil;
    
    NSError *error;
    NSDictionary * obj = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    
    if (obj != nil && error == nil)
    {
        return obj;
    }else
    {
        return nil;
    }
}

//json Data to Dic 2 我写
+(NSDictionary *)dicWithJsonString:(NSString *)jsonString{
    
    if (jsonString.length == 0) return nil;
    
    NSError *error;
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (dic != nil && error == nil) {
        return dic;
    }else{
        return nil;
    }
}

//json Data to array
+(NSArray *)jsonArrFrom:(NSData *)data{
    
   if (data.length == 0) return nil;
    
    NSError *error;
    NSArray* obj = (NSArray *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    if (obj != nil && error == nil) {
        return obj;
    }else{
        return nil;
    }
}
//Dic to json Data
+(NSData *)jsonDataFromDic:(NSDictionary *)dic{
    if ([NSJSONSerialization isValidJSONObject:dic]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
        if (jsonData.length>0&&error==nil) {
            return jsonData;
        }else{
            return nil;
        }
        
    }else{
        return nil;
    }
}
//Arr to json Data
+(NSData *)jsonDataFromArr:(NSArray *)arr {
    if ([NSJSONSerialization isValidJSONObject:arr]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
        if (jsonData.length>0&&error==nil) {
            return jsonData;
        }else{
            return nil;
        }
    }else{
        return nil;
    }
}




@end
